/**
 * @description 智能翻译网页
 * @author libin
 * @date 2025-08-25
 * @version 1.0.0
 */

// 存储最后鼠标位置
let lastMouseX = 0;
let lastMouseY = 0;

// 监听鼠标移动
document.addEventListener('mousemove', (e) => {
    lastMouseX = e.clientX;
    lastMouseY = e.clientY;
});

// 监听来自background的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log("收到来自后台的消息:", request);

    if (request.action === "copyDivContent") {
        console.log("开始处理翻译请求...");

        // 使用Promise确保正确处理异步操作
        handleCopyDivContent()
            .then(result => {
                console.log("翻译完成:", result);
                sendResponse(result);
            })
            .catch(error => {
                console.error("翻译失败:", error);
                sendResponse({
                    status: "error",
                    message: error.message || "翻译失败"
                });
            });

        // 返回true表示将异步发送响应
        return true;
    }

    sendResponse({status: "unknown_request"});
});

// 处理复制操作的异步函数
async function handleCopyDivContent() {
    try {
        // 优先获取用户选中的文字
        const selectedText = window.getSelection().toString().trim();
        if (selectedText) {
            console.log("使用选中的文字:", selectedText);
            showContentPopup(selectedText, null);
            return {status: "success"};
        }

        // 如果没有选中文字，则获取鼠标位置的元素
        const element = document.elementFromPoint(lastMouseX, lastMouseY);
        console.log("找到的元素:", element);
        if (!element) {
            return {status: "fail", message: "未找到元素"};
        }
        let textToCopy = element.textContent.trim();

        // 向上查找最近的div
        let targetDiv = element.closest('div');
        console.log("找到的div:", targetDiv);
        if (targetDiv) {
            // 获取div文本内容
            textToCopy = targetDiv.textContent.trim();
        } else {
            targetDiv = element;
            console.log("未找到div元素，使用鼠标位置的元素:", element);
        }
        if (!textToCopy) {
            return {status: "fail", message: "div内容为空"};
        }

        highlightDiv(targetDiv);
        showContentPopup(textToCopy, targetDiv);
        return {status: "success"};
    } catch (error) {
        console.error("处理内容时出错:", error);
        throw error;
    }
}

// 高亮显示被复制的div
function highlightDiv(targetDiv) {
    // const element = document.elementFromPoint(lastMouseX, lastMouseY);
    // const targetDiv = element.closest('div');

    if (!targetDiv) {
        console.log("高亮时未找到div");
        return;
    }

    // 保存原始样式
    const originalBorder = targetDiv.style.border;
    const originalTransition = targetDiv.style.transition;

    // 添加高亮样式
    targetDiv.style.border = '2px solid #4CAF50';
    targetDiv.style.transition = 'border 0.5s ease';

    // 3秒后恢复原始样式
    setTimeout(() => {
        targetDiv.style.border = originalBorder;
        targetDiv.style.transition = originalTransition;
    }, 1500);
}

// 调用doubao-1-5-lite-32k-250115模型API接口翻译内容
async function translateContentWithDoubao(content) {
    try {
        // 使用配置文件中的API配置
        const response = await fetch(API_CONFIG.ENDPOINT, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${API_CONFIG.API_KEY}`
            },
            body: JSON.stringify({
                model: API_CONFIG.MODEL_ID,
                messages: [
                    {
                        role: 'system',
                        content: '你是一个翻译专家，将请求内容翻译成中文，并以markdown格式返回。'
                    },
                    {
                        role: 'user',
                        content: content
                    }
                ],
                temperature: API_CONFIG.DEFAULT_PARAMS.temperature,
                max_tokens: API_CONFIG.DEFAULT_PARAMS.max_tokens
            })
        });

        if (!response.ok) {
            throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
        }

        const data = await response.json();
        console.log("doubao模型API返回:", data);

        // 根据实际API响应结构调整
        if (data.choices && data.choices.length > 0) {
            return data.choices[0].message.content.trim();
        } else {
            throw new Error('API返回格式不正确');
        }
    } catch (error) {
        console.error("调用doubao模型API失败:", error);
        throw new Error("翻译服务暂时不可用");
    }
}


function showContentPopup(content, sourceElement) {
    // 移除现有的弹窗（如果有）
    const existingPopup = document.getElementById('div-content-popup');
    if (existingPopup) {
        existingPopup.remove();
    }

    // 创建弹窗元素
    const popup = document.createElement('div');
    popup.id = 'div-content-popup';

    // 设置弹窗样式为居中显示，调整边距，并添加可调整大小的样式
    popup.style.cssText = `
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: min(600px, 90vw);
    height: 70vh;
    min-width: 300px;
    min-height: 200px;
    background: white;
    border: 1px solid #ccc;
    border-radius: 8px;
    box-shadow: 0 6px 20px rgba(0,0,0,0.2);
    padding: 0;
    z-index: 10000;
    font-family: Arial, sans-serif;
    font-size: 14px;
    line-height: 1.4;
    color: #333;
    overflow: hidden;
    transition: opacity 0.3s ease;
    resize: both; /* 添加可调整大小功能 */
  `;

    // 创建可拖拽的标题栏容器
    const titleContainer = document.createElement('div');
    titleContainer.style.cssText = `
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    padding: 12px 16px;
    border-bottom: 1px solid #eee;
    color: #4CAF50;
    font-size: 16px;
    background: #f9f9f9;
    cursor: move;
    user-select: none;
  `;

    // 创建标题文本
    const titleText = document.createElement('div');
    titleText.textContent = '翻译网页';
    titleText.style.cssText = `
    flex-grow: 1;
  `;

    // 创建关闭按钮
    const closeBtn = document.createElement('div');
    closeBtn.innerHTML = '&times;';
    closeBtn.style.cssText = `
    font-size: 24px;
    font-weight: normal;
    cursor: pointer;
    color: #999;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
  `;

    closeBtn.onmouseover = () => {
        closeBtn.style.backgroundColor = '#eee';
        closeBtn.style.color = '#333';
    };
    closeBtn.onmouseout = () => {
        closeBtn.style.backgroundColor = '';
        closeBtn.style.color = '#999';
    };

    // 关闭弹窗功能
    closeBtn.onclick = () => {
        popup.style.opacity = '0';
        setTimeout(() => popup.remove(), 300);
    };

    // 组装标题栏
    titleContainer.appendChild(titleText);
    titleContainer.appendChild(closeBtn);

    // 创建内容容器
    const contentContainer = document.createElement('div');
    contentContainer.style.cssText = `
    padding: 12px;
    height: calc(100% - 50px); /* 减去标题栏高度 */
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
  `;

    // 创建内容区域，增加高度
    const contentDiv = document.createElement('div');
    contentDiv.textContent = '正在翻译...';
    contentDiv.style.cssText = `
    white-space: pre-wrap;
    word-break: break-word;
    flex: 1;
    overflow-y: auto;
    font-size: 14px;
    line-height: 1.5;
  `;

    // 添加到内容容器
    contentContainer.appendChild(contentDiv);

    // 添加到弹窗
    popup.appendChild(titleContainer);
    popup.appendChild(contentContainer);

    // 添加到页面
    document.body.appendChild(popup);

    // 添加拖拽功能
    let isDragging = false;
    let startX, startY, initialX, initialY;

    // 鼠标按下事件
    titleContainer.addEventListener('mousedown', dragStart);

    // 鼠标移动事件
    document.addEventListener('mousemove', drag);

    // 鼠标释放事件
    document.addEventListener('mouseup', dragEnd);

    function dragStart(e) {
        // 避免点击关闭按钮时触发拖拽
        if (e.target === closeBtn) {
            return;
        }

        isDragging = true;

        // 获取初始鼠标位置
        startX = e.clientX;
        startY = e.clientY;

        // 获取弹窗当前的位置
        const rect = popup.getBoundingClientRect();
        initialX = rect.left;
        initialY = rect.top;

        // 防止文本选中
        e.preventDefault();
    }

    function drag(e) {
        if (!isDragging) return;

        // 计算移动距离
        const dx = e.clientX - startX;
        const dy = e.clientY - startY;

        // 更新弹窗位置
        popup.style.left = `${initialX + dx}px`;
        popup.style.top = `${initialY + dy}px`;
        popup.style.transform = 'none'; // 移除居中transform

        e.preventDefault();
    }

    function dragEnd() {
        isDragging = false;
    }

    // 添加ESC键关闭功能
    const closeOnEsc = (e) => {
        if (e.key === 'Escape') {
            popup.style.opacity = '0';
            setTimeout(() => {
                popup.remove();
                document.removeEventListener('keydown', closeOnEsc);
            }, 300);
        }
    };

    document.addEventListener('keydown', closeOnEsc);

    // 调用翻译API
    translateContentWithDoubao(content)
        .then(translated => {
            // 使用自定义Markdown解析器渲染内容
            const htmlContent = markdownToHtml(translated);
            contentDiv.innerHTML = htmlContent;

            // 添加Markdown样式
            addMarkdownStyles(contentDiv);
        })
        .catch(error => {
            console.error("翻译失败:", error);
            contentDiv.innerHTML = `
                <div style="font-weight: bold; margin-bottom: 5px; color: #666;">翻译结果:</div>
                <div style="white-space: pre-wrap; word-break: break-word; font-size: 14px; line-height: 1.5; color: #f44336;">
                    翻译失败: ${error.message}
                </div>
            `;
        });
}



// Markdown到HTML的转换逻辑
function markdownToHtml(markdown) {
    if (!markdown) return '';

    // 先标准化换行符
    let html = markdown.replace(/\r\n/g, '\n').replace(/\r/g, '\n');

    // 存储代码块
    const codeBlocks = [];

    // 提取代码块（包括语言标识）
    html = html.replace(/```([\s\S]*?)```/g, function(match, content) {
        // 保存代码块并返回占位符
        codeBlocks.push(content);
        return `@@CODE_BLOCK_${codeBlocks.length - 1}@@`;
    });

    // 按行处理文本
    const lines = html.split('\n');
    const processedLines = [];
    let inList = false;
    let listType = ''; // 'ul' 或 'ol'
    let inBlockquote = false;
    let inTable = false;
    let tableHeaders = [];
    let tableAligns = [];
    let tableRows = [];

    for (let i = 0; i < lines.length; i++) {
        let line = lines[i];

        // 处理代码块占位符
        if (line.includes('@@CODE_BLOCK_')) {
            if (inList) {
                processedLines.push(`</${listType}>`);
                inList = false;
                listType = '';
            }
            if (inBlockquote) {
                processedLines.push('</blockquote>');
                inBlockquote = false;
            }
            if (inTable) {
                // 结束表格
                processedLines.push(buildTable(tableHeaders, tableAligns, tableRows));
                inTable = false;
                tableHeaders = [];
                tableAligns = [];
                tableRows = [];
            }
            processedLines.push(line);
            continue;
        }

        // 处理空行
        if (line.trim() === '') {
            if (inList) {
                processedLines.push(`</${listType}>`);
                inList = false;
                listType = '';
            }
            if (inBlockquote) {
                processedLines.push('</blockquote>');
                inBlockquote = false;
            }
            if (inTable) {
                // 空行结束表格
                processedLines.push(buildTable(tableHeaders, tableAligns, tableRows));
                inTable = false;
                tableHeaders = [];
                tableAligns = [];
                tableRows = [];
            }
            // 不再添加空行，使内容更紧凑
            continue;
        }

        // 检查是否是表格分隔行
        if (isTableSeparator(line)) {
            if (inTable) {
                // 表格分隔行已经处理过了
                continue;
            }

            // 开始表格处理
            inTable = true;
            tableHeaders = (i > 0 ? lines[i-1] : '').split('|').map(cell => cell.trim()).filter(cell => cell);
            tableAligns = parseTableAligns(line);
            tableRows = [];

            // 移除表头行（已经在headers中处理）
            if (processedLines.length > 0) {
                // 重要：清除表头行前的空行，避免表格前出现过多空行
                while (processedLines.length > 0 && processedLines[processedLines.length - 1] === '') {
                    processedLines.pop();
                }
                // 移除表头行本身
                if (processedLines.length > 0) {
                    processedLines.pop();
                }
            }
            continue;
        }

        // 处理表格行
        if (inTable && line.includes('|')) {
            const rowCells = line.split('|').map(cell => cell.trim()).filter(cell => cell);
            if (rowCells.length > 0) {
                tableRows.push(rowCells);
            }
            continue;
        } else if (inTable) {
            // 表格结束
            processedLines.push(buildTable(tableHeaders, tableAligns, tableRows));
            inTable = false;
            tableHeaders = [];
            tableAligns = [];
            tableRows = [];
        }

        // 处理块引用
        if (line.startsWith('> ')) {
            if (inList) {
                processedLines.push(`</${listType}>`);
                inList = false;
                listType = '';
            }
            if (!inBlockquote) {
                processedLines.push('<blockquote>');
                inBlockquote = true;
            }
            line = line.substring(2);
            processedLines.push(line);
            continue;
        } else if (inBlockquote) {
            processedLines.push('</blockquote>');
            inBlockquote = false;
        }

        // 处理无序列表
        if (/^[\*\-\+]\s/.test(line)) {
            if (inList && listType !== 'ul') {
                processedLines.push(`</${listType}>`);
                inList = false;
            }
            if (!inList) {
                processedLines.push('<ul>');
                inList = true;
                listType = 'ul';
            }
            line = line.replace(/^[\*\-\+]\s/, '');
            processedLines.push(`<li>${line}</li>`);
            continue;
        }

        // 处理有序列表
        if (/^\d+\.\s/.test(line)) {
            if (inList && listType !== 'ol') {
                processedLines.push(`</${listType}>`);
                inList = false;
            }
            if (!inList) {
                processedLines.push('<ol>');
                inList = true;
                listType = 'ol';
            }
            line = line.replace(/^\d+\.\s/, '');
            processedLines.push(`<li>${line}</li>`);
            continue;
        }

        // 结束列表
        if (inList) {
            processedLines.push(`</${listType}>`);
            inList = false;
            listType = '';
        }

        // 处理标题
        if (line.startsWith('# ')) {
            processedLines.push(`<h1>${line.substring(2)}</h1>`);
        } else if (line.startsWith('## ')) {
            processedLines.push(`<h2>${line.substring(3)}</h2>`);
        } else if (line.startsWith('### ')) {
            processedLines.push(`<h3>${line.substring(4)}</h3>`);
        } else if (line.startsWith('#### ')) {
            processedLines.push(`<h4>${line.substring(5)}</h4>`);
        } else if (line.startsWith('##### ')) {
            processedLines.push(`<h5>${line.substring(6)}</h5>`);
        } else if (line.startsWith('###### ')) {
            processedLines.push(`<h6>${line.substring(7)}</h6>`);
        }
        // 处理水平线
        else if (/^---+$|^___+$|^\*\*\*+$/.test(line.trim())) {
            processedLines.push('<hr />');
        }
        // 处理普通段落
        else {
            processedLines.push(line);
        }
    }

    // 关闭任何打开的标签
    if (inList) {
        processedLines.push(`</${listType}>`);
    }
    if (inBlockquote) {
        processedLines.push('</blockquote>');
    }
    if (inTable) {
        processedLines.push(buildTable(tableHeaders, tableAligns, tableRows));
    }

    // 重新组合文本
    html = processedLines.join('\n');

    // 处理行内元素
    // 处理粗体和斜体（注意顺序很重要）
    html = html.replace(/\*\*\*(.*?)\*\*\*/g, '<strong><em>$1</em></strong>');
    html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');

    // 处理内联代码
    html = html.replace(/`([^`]+)`/g, '<code>$1</code>');

    // 处理链接
    html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');

    // 处理图片
    html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" />');

    // 恢复代码块并处理语言标识
    for (let i = 0; i < codeBlocks.length; i++) {
        const codeContent = codeBlocks[i];
        let language = '';
        let code = codeContent;

        // 检查是否有语言标识
        const firstLineEnd = codeContent.indexOf('\n');
        if (firstLineEnd > 0) {
            const firstLine = codeContent.substring(0, firstLineEnd).trim();
            // 简单判断是否为语言标识（只包含字母、数字、+、#、-）
            if (/^[a-zA-Z0-9+#\-_]+$/.test(firstLine) && firstLine.length < 20) {
                language = firstLine;
                code = codeContent.substring(firstLineEnd + 1);
            }
        }

        // 转义HTML并保留格式
        const escapedCode = escapeHtml(code);
        const codeBlockHtml = `<pre><code${language ? ` class="language-${language}"` : ''}>${escapedCode}</code></pre>`;
        html = html.replace(`@@CODE_BLOCK_${i}@@`, codeBlockHtml);
    }

    // 处理段落：将连续的非标签行包装在<p>标签中
    const paragraphs = html.split('\n');
    const result = [];
    let inParagraph = false;

    for (let i = 0; i < paragraphs.length; i++) {
        const line = paragraphs[i];

        // 空行处理
        if (line === '') {
            if (inParagraph) {
                result.push('</p>');
                inParagraph = false;
            }
            continue;
        }

        // 检查是否是块级元素
        const isBlockElement = /^<(h[1-6]|ul|ol|li|blockquote|pre|hr|img|table)/.test(line.trim()) ||
            line.includes('</ul>') ||
            line.includes('</ol>') ||
            line.includes('</blockquote>') ||
            line.includes('</table>') ||
            line.includes('@@CODE_BLOCK_') ||
            /^<\/(h[1-6]|ul|ol|li|blockquote|pre|hr|img|table)/.test(line.trim());

        if (isBlockElement) {
            if (inParagraph) {
                result.push('</p>');
                inParagraph = false;
            }
            result.push(line);
        } else {
            if (!inParagraph) {
                result.push('<p>');
                inParagraph = true;
            } else {
                result.push('<br />');
            }
            result.push(line);
        }
    }

    if (inParagraph) {
        result.push('</p>');
    }

    html = result.join('');

    // 清理多余的空行和标签
    html = html.replace(/<p>\s*<\/p>/g, '');
    html = html.replace(/\n{3,}/g, '\n\n');

    return html;
}

function isTableSeparator(line) {
    return /^\s*\|?(\s*:?\-+:?\s*\|)+\s*:?\-+:?\s*\|?\s*$/.test(line);
}

function parseTableAligns(line) {
    const cells = line.split('|').map(cell => cell.trim()).filter(cell => cell);
    return cells.map(cell => {
        if (cell.startsWith(':') && cell.endsWith(':')) return 'center';
        if (cell.endsWith(':')) return 'right';
        return 'left';
    });
}

function buildTable(headers, aligns, rows) {
    if (headers.length === 0) return '';

    let tableHtml = '<table>';

    // 添加表头
    tableHtml += '<thead><tr>';
    for (let i = 0; i < headers.length; i++) {
        const align = i < aligns.length ? aligns[i] : 'left';
        tableHtml += `<th style="text-align: ${align}">${headers[i]}</th>`;
    }
    tableHtml += '</tr></thead>';

    // 添加表体
    if (rows.length > 0) {
        tableHtml += '<tbody>';
        for (const row of rows) {
            tableHtml += '<tr>';
            for (let i = 0; i < row.length; i++) {
                const align = i < aligns.length ? aligns[i] : 'left';
                tableHtml += `<td style="text-align: ${align}">${row[i]}</td>`;
            }
            tableHtml += '</tr>';
        }
        tableHtml += '</tbody>';
    }

    tableHtml += '</table>';
    return tableHtml;
}

// HTML转义函数
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// 添加Markdown样式
function addMarkdownStyles(container) {
    const style = document.createElement('style');
    style.textContent = `
        /* Markdown样式 */
        h1, h2, h3, h4, h5, h6 {
            margin-top: 1em;
            margin-bottom: 0.5em;
            font-weight: bold;
        }
        
        h1 { font-size: 1.5em; }
        h2 { font-size: 1.4em; }
        h3 { font-size: 1.3em; }
        h4 { font-size: 1.2em; }
        h5 { font-size: 1.1em; }
        h6 { font-size: 1em; }
        
        p {
            margin-bottom: 1em;
            line-height: 1.6;
        }
        
        ul, ol {
            margin-bottom: 1em;
            padding-left: 2em;
        }
        
        li {
            margin-bottom: 0.5em;
        }
        
        blockquote {
            border-left: 4px solid #ddd;
            padding-left: 1em;
            margin-left: 0;
            color: #666;
            margin-bottom: 1em;
        }
        
        code {
            background-color: #f5f5f5;
            padding: 0.2em 0.4em;
            border-radius: 3px;
            font-family: monospace;
            font-size: 0.9em;
        }
        
        pre {
            background-color: #f5f5f5;
            padding: 1em;
            border-radius: 5px;
            overflow-x: auto;
            margin-bottom: 1em;
        }
        
        pre code {
            background: none;
            padding: 0;
            display: block;
        }
        
        strong {
            font-weight: bold;
        }
        
        em {
            font-style: italic;
        }
        
        a {
            color: #4CAF50;
            text-decoration: underline;
        }
        
        hr {
            border: none;
            border-top: 1px solid #ddd;
            margin: 1em 0;
        }
        
        table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 1em;
        }
        
        th, td {
            border: 1px solid #ddd;
            padding: 0.5em;
            text-align: left;
        }
        
        th {
            background-color: #f5f5f5;
            font-weight: bold;
        }
        
        img {
            max-width: 100%;
            height: auto;
        }
    `;

    container.appendChild(style);
}

// 将函数暴露到全局，以便background直接调用
window.copyDivContent = handleCopyDivContent;

console.log("内容脚本已加载并初始化完成");